Functions
Conditional Expressions
abs :: Int -> Int
abs n = if n >= 0 then n else -n
Can be nested
signum :: Int -> Int
signum n = if n < 0 then -1 else
if n == 0 then 0 else 1
Conditional expressions must always have an else branch, which avoids any possible ....... # 1
Guarded Equations
Alternative is guarded equations
abs n | n >= 0 = n
| otherwise = n
|
means such that
Pattern Matching
Clear definition
not :: Bool -> Bool
not False = True
not True = False
Symbol _
is a while card that matches any argument values.
Patterns are matched in order.
_ && _ = False
True && True = True
Any 2 arguments would satisfy the first one, so True would never be outputted Patterns may not repeat variables.
List Patterns
- Internally, every non-empty list is constructed by repeated use of an (:) called 'cons' that adds an element to the start of a list
- Functions on lists can be defined used
x:xs
patterns x:xs
patterns only match non-empty lists- Patterns must be parenthesised, because application has priority over (:)
Lambda Expressions
Constructed without naming the functions by using lambda expressions. Nameless function that takes a number x and returns the result x+x
Typed as \.
Why they're useful
Used to give a formal mean to functions defined using currying Can be used to avoid naming functions that are only referenced once,
Operator Sections
An operator written between its two arguments can be converted into a curried function written before its two arguments by using parentheses.